<script setup lang="ts">
import { MoreOne } from '@icon-park/vue-next'
import uploadSingleImage from '@renderer/components/uploadSingleImage.vue'
import formButton from '@renderer/components/formButton.vue'
import useShareDir from '@renderer/composables/useShareDir'
import useUtil from '@renderer/composables/useUtil'
import { Action, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import helper from '@renderer/utils/helper'
const route = useRouter()
const { getDirFile, dirFileParams, shareFileList, updateFileName, delDirFile, uploadDocFile, createDocDir } =
  useShareDir()
const currentQuery = route.currentRoute.value.query
const fileDialog = ref(false)
const fileDirDialog = ref(false)
const dirType = ref('create')
const fileForm = reactive({
  file_name: '',
  file_id: 0,
})
const fileDirForm = reactive({
  file_name: '',
  file_id: 0,
})
const handleCloseDialog = () => {
  fileForm.file_name = ''
  fileForm.file_id = 0
  fileDialog.value = false
}
const handleCloseDirDialog = () => {
  fileDirForm.file_name = ''
  fileDirForm.file_id = 0
  fileDirDialog.value = false
}
const handleSubmit = async () => {
  await updateFileName({ file_name: fileForm.file_name, file_id: fileForm.file_id })
  await getDirFile({ dir_id: currentQuery.dir_id, pid: currentQuery.dir_id })
  fileDialog.value = false
}
const handleDirSubmit = async () => {
  if (dirType.value == 'create') {
    await createDocDir({ file_name: fileDirForm.file_name, pid: currentQuery.dir_id })
  } else {
    await updateFileName({ file_name: fileDirForm.file_name, file_id: fileDirForm.file_id })
  }
  fileDirDialog.value = false
  await getDirFile({ dir_id: currentQuery.dir_id, pid: currentQuery.dir_id })
}
const handleFileName = (item: ShareFileModel) => {
  if (item.file_type != 1) {
    fileForm.file_name = item.file_name
    fileForm.file_id = item.id
    fileDialog.value = true
  } else {
    fileDirForm.file_name = item.file_name
    fileDirForm.file_id = item.id
    dirType.value = 'edit'
    fileDirDialog.value = true
  }
}
const handelDelFile = (item: ShareFileModel) => {
  ElMessageBox.alert('是否要删除该文件嘛', '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await delDirFile({ file_id: item.id })
        await getDirFile({ dir_id: currentQuery.dir_id, pid: currentQuery.dir_id })
      }
    },
  })
}

const handleNextPage = async (val: number) => {
  await getDirFile({ page: val, dir_id: currentQuery.dir_id, pid: currentQuery.dir_id })
}
const downloadFile = (item: ShareFileModel) => {
  window.api.downloadFile(item.file_url, item.file_name)
}
const previewImg = (fileUrl: string) => {
  const fileType = fileUrl.split('.').pop()
  switch (fileType) {
    case 'jpg':
    case 'png':
    case 'webp':
      return [fileUrl]
    default:
      return []
  }
}
const openFileDir = (item: ShareFileModel) => {
  window.api.closeWindow('filePages', 'destroy')
  window.api.openWindow('filePages', { dir_id: item.id, title: item.file_name })
}
const avatarFinish = async (fileInfo: UploadResult) => {
  await uploadDocFile({
    pid: currentQuery.dir_id,
    file_name: fileInfo.file_name,
    file_url: fileInfo.src,
    file_size: fileInfo.file_size,
  })
  await getDirFile({ dir_id: currentQuery.dir_id, page: shareFileList.value?.current_page, pid: currentQuery.dir_id })
}
const handleCreateDir = () => {
  dirType.value = 'create'
  fileDirForm.file_id = 0
  fileDirForm.file_name = ''
  fileDirDialog.value = true
}
const { handlePic } = useUtil()
const { checkRule } = helper()
await getDirFile({ dir_id: currentQuery.dir_id, pid: currentQuery.dir_id })
</script>

<template>
  <main
    class="bg-white flex flex-col py-4 px-3 gap-2 relative rounded-md overflow-hidden nodrag"
    style="height: -webkit-fill-available">
    <div class="flex justify-end gap-3" v-if="checkRule('共享文档管理权')">
      <uploadSingleImage @finish="avatarFinish" />
      <formButton @click="handleCreateDir"> 新建文件夹 </formButton>
    </div>
    <div class="grid gap-x-5 md:grid-cols-6 xl:grid-cols-7">
      <div
        class="flex flex-col items-center justify-center gap-4 py-6 overflow-hidden hover:bg-[#f5f5f5] hover:rounded-md relative group"
        v-for="(item, index) in shareFileList?.data"
        :key="index">
        <el-image
          v-if="item.file_type != 1"
          class="w-[90px] h-[90px]"
          :src="handlePic(item.file_url, item.file_type)"
          :zoom-rate="1.2"
          :max-scale="1"
          :min-scale="0.2"
          :preview-src-list="previewImg(item.file_url)"
          :initial-index="4"
          hide-on-click-modal
          fit="cover" />
        <img src="@renderer/public/fileDir.jpg" style="width: 122px; height: 98px" @dblclick="openFileDir(item)" v-else />
        <span class="text-black text-base one-line">{{ item.file_name }}</span>
        <el-dropdown
          trigger="hover"
          class="bg-white rounded-md absolute right-2 top-2 hidden group-hover:block"
          v-if="checkRule('共享文档管理权') || checkRule('共享文档下载权')">
          <MoreOne theme="outline" size="24" class="cursor-pointer" fill="#000000" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="downloadFile(item)" v-if="checkRule('共享文档下载权') && item.file_type != 1">
                下载
              </el-dropdown-item>
              <el-dropdown-item @click="handleFileName(item)" v-if="checkRule('共享文档管理权')">
                重命名
              </el-dropdown-item>
              <el-dropdown-item @click="handelDelFile(item)" v-if="checkRule('共享文档管理权')">删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <el-pagination
      @current-change="handleNextPage"
      :current-page="shareFileList?.current_page"
      :page-size="dirFileParams.limit"
      :total="shareFileList?.total"
      background
      class="flex-1 items-end" />
    <el-dialog v-model="fileDialog" width="500" align-center :show-close="false">
      <div class="text-center text-black font-bold text-xl mb-8">修改文件</div>
      <el-form :model="fileForm" inline>
        <el-form-item label="文件名称：">
          <el-input v-model="fileForm.file_name" placeholder="请输入文件名称" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="pt-6 flex gap-10 justify-center">
          <formButton @click="handleCloseDialog"> 取消 </formButton>
          <formButton @click="handleSubmit"> 确定 </formButton>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="fileDirDialog" width="500" align-center :show-close="false">
      <div class="text-center text-black font-bold text-xl mb-8">
        {{ dirType == 'create' ? '创建文件夹' : '修改文件夹' }}
      </div>
      <el-form inline>
        <el-form-item label="文件夹名称：">
          <el-input v-model="fileDirForm.file_name" placeholder="请输入文件夹名称" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="pt-6 flex gap-10 justify-center">
          <formButton @click="handleCloseDirDialog"> 取消 </formButton>
          <formButton @click="handleDirSubmit"> 确定 </formButton>
        </div>
      </template>
    </el-dialog>
  </main>
</template>
<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 0px !important;
  flex: 1;
}
</style>
